<template>
  <div ref="editorContainer" class="editor-containers" style="height: 380px; overflow: auto">
    <!-- style="height: 350px;overflow: auto;" -->
    <view class="aie-container">
      <view class="aie-container-header"></view>
      <view class="aie-container-main"></view>
      <view class="aie-container-footer" style="display: none"></view>
    </view>
  </div>
</template>

<script>
import { AiEditor } from 'aieditor'
import { getToken } from '@/utils/webStorage'


// 获取host.js中的FILE_URL
const FILE_URL = window.hosts.FILE_URL[import.meta.env.MODE]
export default {
  props: {
    content: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      editorContainer: null,
      aiEditor: null,
      token: '',
    }
  },
  mounted() {
    this.token = getToken() || ''
    // 确保DOM已加载
    this.$nextTick(() => {
      setTimeout(() => {
        this.initAiEditor()
      }, 100)
    })
  },
  beforeDestroy() {
    this.destroyShareaiEditorl()
  },

  methods: {
    getContent() {
      return this.aiEditor ? this.aiEditor.getHtml() : ''
    },
    setContent(content) {
      if (this.aiEditor) {
        return this.aiEditor.setContent(content)
      }
    },
    destroyShareaiEditorl() {
      if (this.aiEditor) {
        //  destroy 方法，直接清空 DOM 并置空引用
        this.aiEditor.setContent('')
        this.aiEditor.destroy()
        this.aiEditor = null
      }
    },
    initAiEditor() {
      try {
        // 如果已存在，先销毁
        if (this.aiEditor) {
          this.destroyShareaiEditorl()
        }
        this.$nextTick(() => {
          // this.aiEditor = new AiEditor(this.$refs.editorContainer);
          this.aiEditor = new AiEditor({
            draggable: false,
            element: this.$refs.editorContainer,
            placeholder: '点击输入内容...',
            // content: "AiEditor 是一个面向 AI 的开源富文本编辑器。 ",
            toolbarKeys: [
              'undo',
              'redo',
              '|',
              'heading',
              'font-family',
              'font-size',
              '|',
              'bold',
              'italic',
              'underline',
              'strike',
              'link',
              'code',
              // "subscript",
              // "superscript",
              'hr',
              'todo',
              'emoji',
              '|',
              'highlight',
              'font-color',
              '|',
              'align',
              'line-height',
              '|',
              'bullet-list',
              'ordered-list',
              'indent-decrease',
              'indent-increase',
              'break',
              '|',
              'image',
              'video',
              'attachment',
              'quote',
              'code-block',
              'table',
              '|',
              'fullscreen',
            ],
            image: {
              // allowBase64: true,
              // defaultSize: 350,
              uploadUrl: `${FILE_URL}/app/common/upload`,
              uploadFormName: 'Image', //上传时的文件表单名称
              uploadHeaders: {
                token: this.token,
              },
              uploaderEvent: {
                onSuccess: (file, response) => {
                  //监听图片上传成功
                  //注意：
                  // 1、如果此方法返回 false，则图片不会被插入到编辑器
                  // 2、可以在这里返回一个新的 json 给编辑器
                  return {
                    errorCode: 0,
                    data: {
                      src: response.result,
                    },
                  }
                },
              },
              bubbleMenuItems: ['AlignLeft', 'AlignCenter', 'AlignRight', 'delete'],
            },
            video: {
              uploadUrl: `${FILE_URL}/app/common/upload`,
              uploadFormName: 'Image', //上传时的文件表单名称
              uploadHeaders: {
                token: this.token,
              },
              uploaderEvent: {
                onSuccess: (file, response) => {
                  return {
                    errorCode: 0,
                    data: {
                      src: response.result,
                    },
                  }
                },
              },
            },
            attachment: {
              uploadUrl: `${FILE_URL}/app/common/upload`,
              uploadFormName: 'Image', //上传时的文件表单名称
              uploadHeaders: {
                token: this.token,
              },
              uploaderEvent: {
                onSuccess: (file, response) => {
                  return {
                    errorCode: 0,
                    data: {
                      href: response.result,
                    },
                  }
                },
              },
            },
          })
          console.log(this.content)

          if (this.content) {
            this.aiEditor.setContent(this.content)
          }
        })
      } catch (error) {
        console.error('初始化Quill编辑器失败:', error)
        // 如果初始化失败，可以提供一个简单的textarea作为备选
        // this.initFallbackEditor();
      }
    },

    initFallbackEditor() {
      // 备选编辑器：如果Quill初始化失败，使用简单的textarea
      //   const container = this.$refs.editorContainer;
      //   if (container) {
      //     container.innerHTML = `
      // 		<textarea
      // 		  placeholder="请输入内容..."
      // 		  style="width: 100%; min-height: 200px; padding: 10px; border: 1px solid #ddd; border-radius: 4px;"
      // 		  oninput="this.parentElement.dataset.content = this.value"
      // 		></textarea>
      // 	  `;
      //     const textarea = container.querySelector("textarea");
      //     textarea.addEventListener("input", (e) => {
      //       this.formData.brief = e.target.value;
      //     });
      //   }
    },
  },
}
</script>
<style lang="scss" scoped>
.aie-container {
  overflow: auto;
}
</style>
